package game;

import javax.imageio.ImageIO;
import characters.Fighter;
import characters.CharacterFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;

public class FightPanel extends JPanel implements KeyListener {
    private GameWindow gameWindow;
    private Fighter player;
    private Fighter enemy;
    private Timer gameTimer;
    private BufferedImage background;
    private boolean[] keysPressed = new boolean[256]; // 跟踪按键状态

    // 游戏区域边界
    private static final int GROUND_LEVEL = 200;
    private static final int LEFT_BOUNDARY = 50;
    private static final int RIGHT_BOUNDARY = 700;

    public FightPanel(GameWindow gameWindow, String playerCharacter, String enemyCharacter) {
        this.gameWindow = gameWindow;

        // 使用角色工厂创建角色
        this.player = CharacterFactory.createCharacter(playerCharacter, 100, GROUND_LEVEL);
        this.enemy = CharacterFactory.createCharacter(enemyCharacter, 600, GROUND_LEVEL);

        setFocusable(true);
        addKeyListener(this);

        // 加载背景图片
        InputStream is = getClass().getResourceAsStream("/background.png");
        if (is != null) {
            try {
                background = ImageIO.read(is);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            System.err.println("无法加载图片资源");
        }
          //  background = ImageLoader.loadImage("resources/background.png");

        // 设置游戏主循环 (60FPS)
        gameTimer = new Timer(16, e -> {
            updateGame();
            repaint();
        });
        gameTimer.start();
    }
    private boolean gameOver = false;
    private long gameOverTime = 0;
    private static final long GAME_OVER_DELAY = 3000; // 3秒
    private Fighter winner;
    private void updateGame() {
        // 处理玩家输入
        if (player.isAlive() && enemy.isAlive())
            handleInput();

        if (gameOver) {
            // 检查3秒是否已过
            if (System.currentTimeMillis() - gameOverTime >= 3000) {
                gameTimer.stop();
                gameWindow.gameOver(player.isAlive());
            }
            return;
        }
        // 更新角色状态
        if (player.isAlive() && enemy.isAlive()) {
            player.updateEffects();
            enemy.updateEffects();

            player.update();
            enemy.update();
        }
        // 更新所有角色效果
        if (player.isAlive() && enemy.isAlive()) {
            player.updateEffects();
            enemy.updateEffects();
        }
        // AI行为
        updateEnemyAI();

        // 检测战斗碰撞
        checkFightCollisions();

        // 检查游戏结束
        if (!player.isAlive() || !enemy.isAlive()) {
            winner = (!player.isAlive()) ? enemy : player;

            // 标记游戏结束并记录时间
            gameOver = true;
            gameOverTime = System.currentTimeMillis();

           // winner.changeState(Fighter.FighterState.IDLE);

        }
    }

    private void handleInput() {
        // 左右移动
        if (keysPressed[KeyEvent.VK_A]) {
            player.moveLeft();
            // 确保不超出左边界
            if (player.getX() < LEFT_BOUNDARY) {
                player.setX(LEFT_BOUNDARY);
            }
        }
        else if (keysPressed[KeyEvent.VK_D]) {
            player.moveRight();
            // 确保不超出右边界
            if (player.getX() > RIGHT_BOUNDARY) {
                player.setX(RIGHT_BOUNDARY);
            }
        }
        else if (player.getCurrentState() == Fighter.FighterState.WALK) {
            // 如果没有按移动键且当前是行走状态，回到站立状态
            player.changeState(Fighter.FighterState.IDLE);
        }

        // 检查Shift键是否按下（用于冲刺）
        boolean shiftPressed = keysPressed[KeyEvent.VK_SHIFT];
        // 左右移动和冲刺
        if (keysPressed[KeyEvent.VK_A]) {
            if (shiftPressed) {
                player.dashBackward();
                // 确保不超出左边界
                if (player.getX() < LEFT_BOUNDARY) {
                    player.setX(LEFT_BOUNDARY);
                }
            } else {
                player.moveLeft();
                // 确保不超出左边界
                if (player.getX() < LEFT_BOUNDARY) {
                    player.setX(LEFT_BOUNDARY);
                }
            }
        }
        else if (keysPressed[KeyEvent.VK_D]) {
            if (shiftPressed) {
                player.dashForward();
                // 确保不超出右边界
                if (player.getX() > RIGHT_BOUNDARY) {
                    player.setX(RIGHT_BOUNDARY);
                }
            } else {
                player.moveRight();
                // 确保不超出右边界
                if (player.getX() > RIGHT_BOUNDARY) {
                    player.setX(RIGHT_BOUNDARY);
                }
            }
        }
        else if (player.getCurrentState() == Fighter.FighterState.WALK ||
                player.getCurrentState() == Fighter.FighterState.DASH) {
            // 如果没有按移动键且当前是行走或冲刺状态，回到站立状态
            player.changeState(Fighter.FighterState.IDLE);
        }

        // 跳跃
        if (keysPressed[KeyEvent.VK_W]) {
            player.jump();
        }

        // 防御
        if (keysPressed[KeyEvent.VK_S]) {
            player.block();
        } else if (player.getCurrentState() == Fighter.FighterState.BLOCK) {
            player.changeState(Fighter.FighterState.IDLE);

        }
    }

    private void updateEnemyAI() {
        // 简单AI逻辑
        if (enemy.isAlive()) {
            // 随机决定行为
            double rand = Math.random();

            if (rand < 0.01) { // 1%几率攻击
                    enemy.attack();
            }
            else if (rand < 0.02) { // 1%几率跳跃
                if (enemy.isGrounded()) {
                    enemy.jump();
                }
            }
            else if (rand < 0.03) { // 1%几率防御
                enemy.block();
            }
            else if (rand < 0.1) { // 5%几率移动
                // 向玩家移动
                if (player.getX() < enemy.getX() - 50) {
                    enemy.moveLeft();
                }
                else if (player.getX() > enemy.getX() + 50) {
                    enemy.moveRight();
                }
            }
            else if (enemy.getCurrentState() == Fighter.FighterState.WALK) {
                enemy.changeState(Fighter.FighterState.IDLE);
            }

        }
    }

    private void checkFightCollisions() {
        // 玩家攻击判定
        if (    (player.isAttacking() || player.getCurrentState() == Fighter.FighterState.KICK) &&
                player.getAttackBox() != null &&
                player.getAttackBox().intersects(enemy.getHitBox()) &&
                player.canHit() &&
                enemy.getCurrentState() != Fighter.FighterState.DOWN) {
            Rectangle2D attackBox = player.getAttackBox();
            int hitX = (int)(attackBox.getCenterX());
            int hitY = (int)(attackBox.getCenterY());
            enemy.takeHit(player.getAttackDamage(), hitX, hitY,player);
            player.recordHit();
        }

        // 敌人攻击判定
        if (    enemy.isAttacking() && enemy.getAttackBox() != null &&
                enemy.getAttackBox().intersects(player.getHitBox())&&
                enemy.canHit()&&
                player.getCurrentState() != Fighter.FighterState.DOWN) {
            Rectangle2D attackBox = enemy.getAttackBox();
            int hitX = (int)(attackBox.getCenterX());
            int hitY = (int)(attackBox.getCenterY());
            player.takeHit(enemy.getAttackDamage(), hitX, hitY,enemy);
            enemy.recordHit();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // 绘制背景
        if (background != null) {
            g2d.drawImage(background, 0, 0, getWidth(), getHeight(), null);
        } else {
            g2d.setColor(Color.BLACK);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }

        // 绘制角色
        player.draw(g2d);
        enemy.draw(g2d);

        // 然后绘制效果（在上层）
        if (player.isAlive() && enemy.isAlive()) {
            player.updateEffects();
            enemy.updateEffects();

            player.drawEffects(g2d);
            enemy.drawEffects(g2d);
        }
        // 绘制血条
        drawHealthBar(g2d, 50, 30, 300, 20, player.getHealth(), "玩家: " + player.getName());
        drawHealthBar(g2d, 450, 30, 300, 20, enemy.getHealth(), "电脑: " + enemy.getName());

        // 绘制操作提示
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        g2d.drawString("操作: 方向键移动, 上键跳跃, 下键防御, J攻击", 50, 550);

        // 调试信息
        if (GameWindow.DEBUG_MODE) {
            g2d.drawString("玩家状态: " + player.getCurrentState(), 50, 570);
            g2d.drawString("敌人状态: " + enemy.getCurrentState(), 450, 570);
        }

        if (isPaused) {
            // 绘制暂停时的遮罩效果
        //    g2d.setColor(new Color(0, 0, 0, 50));
      //      g2d.fillRect(0, 0, getWidth(), getHeight());

            // 绘制"暂停"文字
            g2d.setColor(Color.WHITE);
            g2d.setFont(new Font("微软雅黑", Font.BOLD, 48));
            String text = "游戏暂停";
            int textWidth = g2d.getFontMetrics().stringWidth(text);
            g2d.drawString(text, (getWidth() - textWidth)/2, getHeight()/2);
        }

        // 如果游戏结束，显示倒计时
        if (gameOver) {
            float alpha = 0.5f * (System.currentTimeMillis() - gameOverTime) / 3000f;
            g2d.setColor(new Color(0, 0, 0, Math.min(alpha, 0.5f)));
            g2d.fillRect(0, 0, getWidth(), getHeight());

            // 显示"K.O."文字
            g2d.setColor(Color.RED);
            g2d.setFont(new Font("Arial", Font.BOLD, 72));
            String koText = "K.O.";
            int textWidth = g2d.getFontMetrics().stringWidth(koText);
            g2d.drawString(koText, (getWidth() - textWidth)/2, getHeight()/2);
        }


    }

    private boolean isPaused = false;
    public void pauseGame() {
        isPaused = true;
        if (gameTimer != null) {
            gameTimer.stop();
        }
        requestFocus(); // 确保能接收按键事件
    }

    public void resumeGame() {
        isPaused = false;
        if (gameTimer != null) {
            gameTimer.start();
        }
        requestFocus();
    }




    private void drawHealthBar(Graphics2D g2d, int x, int y, int width, int height, int health, String label) {
        // 背景
        g2d.setColor(Color.BLACK);
        g2d.fillRect(x - 1, y - 1, width + 2, height + 2);

        // 血量背景
        g2d.setColor(Color.RED);
        g2d.fillRect(x, y, width, height);

        // 当前血量
        float healthPercent = (float)health / 100;
        g2d.setColor(healthPercent > 0.6f ? Color.GREEN :
                healthPercent > 0.3f ? Color.YELLOW : Color.PINK);
        g2d.fillRect(x, y, (int)(width * healthPercent), height);

        // 边框和标签
        g2d.setColor(Color.WHITE);
        g2d.drawRect(x, y, width, height);
        g2d.drawString(label, x, y - 5);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        keysPressed[e.getKeyCode()] = true;
        // 暂停键
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            if (isPaused) {
                gameWindow.resumeGame();
            } else {
                gameWindow.pauseGame();
            }
        }
        // 攻击键
        if (e.getKeyCode() == KeyEvent.VK_J) {
            player.attack();
        }
        // 处理组合键
        boolean shiftPressed = keysPressed[KeyEvent.VK_SHIFT];
        // 冲刺键
        if (e.getKeyCode() == KeyEvent.VK_D && shiftPressed) {
            player.dashForward();
        }
        else if (e.getKeyCode() == KeyEvent.VK_A && shiftPressed) {
            player.dashBackward();
        }
        // 踢腿键
        else if (e.getKeyCode() == KeyEvent.VK_K) {
            player.kick();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keysPressed[e.getKeyCode()] = false;
        // 释放冲刺键时重置状态
        if (e.getKeyCode() == KeyEvent.VK_SHIFT && player.getCurrentState() == Fighter.FighterState.DASH) {
            player.changeState(Fighter.FighterState.IDLE);
        }
        if ((e.getKeyCode() == KeyEvent.VK_A ||e.getKeyCode() == KeyEvent.VK_D )&& player.getCurrentState() == Fighter.FighterState.DASH) {
            player.changeState(Fighter.FighterState.IDLE);
            player.stopDash();
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}
}